<template>
  <div class="app-container">
    <div class="header">
      <button class="back-button" @click="goBack">
        <svg width="40" height="40" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
          <path d="M19 12H5M12 19L5 12L12 5" stroke="currentColor" stroke-width="2" stroke-linecap="round"
                stroke-linejoin="round"/>
        </svg>
      </button>
      <p class="title">AI简历优化</p>
    </div>
    <!-- 模态框内容 -->
    <el-dialog
        v-model="dialogVisible"
        title="数据配置"
        draggable
        :modal="true"
        :close-on-click-modal="true"
        :close-on-press-escape="true"
        :show-close="false"
        class="left-dialog"
        :before-close="handleClose"
        top="20px"
    >
      <part-data-config
          :selected-module="selectedModule"
          v-if="resumeId !== '' && selectedModuleId"
      />
    </el-dialog>
    <div class="dropdown-row">
      <el-dropdown trigger="click" @command="handleCommand" placement="bottom-start">
        <div class="el-dropdown-link" :class="{ 'has-selection': selecting !== -1 }">
          <el-icon>
            <CirclePlus v-if="selecting === -1"/>
            <DocumentAdd v-else/>
          </el-icon>
          <span style="margin-left: 10px;">{{ selecting === -1 ? '请选择本次投递的简历' : '已选择简历' }}</span>
          <el-icon class="dropdown-arrow">
            <ArrowRight/>
          </el-icon>
        </div>
        <template #dropdown>
          <el-dropdown-menu v-if="!loadingList" class="custom-dropdown">
            <el-dropdown-item :command="-1" class="dropdown-header">
              请选择简历
            </el-dropdown-item>
            <div class="dropdown-divider"></div>
            <div class="dropdown-scrollable">
              <el-dropdown-item
                  v-for="(item, index) in legoCreateList"
                  :key="index"
                  :command="index"
                  class="resume-item"
              >
                <div class="resume-item-date">{{ formatDate(new Date(item.createDate)) }}</div>
                |
                <div class="resume-item-title">{{ item.title }}</div>
              </el-dropdown-item>
            </div>
          </el-dropdown-menu>
          <div v-else class="loading-dropdown">
            <el-icon class="loading-icon"><i class="el-icon-loading"></i></el-icon>
            加载中...
          </div>
        </template>
      </el-dropdown>
    </div>
    <div class="main-content">
      <!-- 左侧简历部分 -->
      <div class="resume-section">
        <div class="resume-preview">
          <div class="resume-container" v-if="selecting!==-1">
            <resume-render></resume-render>
          </div>
          <div v-else class="empty-state">
            <el-icon class="empty-icon">
              <DocumentAdd/>
            </el-icon>
            <h3 class="empty-title">暂无选中的简历</h3>
            <p class="empty-desc">请从上方下拉菜单中选择一份简历来查看详情和优化建议</p>
          </div>
        </div>
        <div class="button-container">
          <button class="save-button" @click="saveResume">保存</button>
          <button class="reanalyse-button" @click="reAnalyse">前往分析</button>
        </div>
      </div>

      <!-- 右侧AI聊天部分 -->
      <div class="ai-chat-section">
        <AIChat :resumeId="getResumeId()"></AIChat>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import {onMounted, ref} from 'vue';
import {ElMessage} from "element-plus";
import {storeToRefs} from "pinia";
import appStore from "@/store";
import AIChat from "@/views/optimizeResume/components/AIChat.vue";
import router from "@/router";
import {ArrowRight, CirclePlus, DocumentAdd} from "@element-plus/icons-vue";
import {getResumeList, getResumeById, getResumeJsonById, updateResume} from "@/http/m_api/template";
import {formatDate} from "@/assets/ts/utils";
import ResumeRender from "@/views/createTemplate/designer/components/ResumeRender.vue";
import {formatListDate, HideNavbar, showNavbar} from "@/utils/common";
import {useGetSelectedModule} from "@/views/createTemplate/designer/hooks/useGetSelectedModule";
import PartDataConfig from "@/views/createTemplate/designer/components/partDataConfig.vue";
import {useRoute} from "vue-router";


const legoCreateList = ref<Array<any>>([]);
const loading = ref(true);
const selecting = ref(-1);
const {HJNewJsonStore, resumeId, selectedModuleId, templateBase} = storeToRefs(appStore.useCreateTemplateStore);
const loadingPreview = ref(false);
const loadingList = ref(false);
const selectedModule = ref()
const route = useRoute();
// Emits
const emits = defineEmits<{
  close: []
}>()

// 响应式数据
const dialogVisible = ref(false)

// 关闭处理
const handleClose = (done: () => void) => {
  selectedModuleId.value = ""
  emits('close')
  done()
}

onMounted(() => {
  resumeId.value = Number.parseInt(route.params.id as string)
  getUserTemplateList()
  HideNavbar()
})

// 保存草稿
let draftTips = ref<string>('');
const saveDataToLocal = () => {
  return new Promise(async (resolve) => {
    const result = await updateResume(Number.parseInt(getResumeId() as string), HJNewJsonStore.value.config.title ,templateBase.value.coverUrl, HJNewJsonStore.value);
    if (result.code === 0) {
      draftTips.value = `已保存：${formatListDate(result.data.updateDate)}`;
      ElMessage({type: 'success', message: '保存成功'})
      resolve('保存草稿成功');
    } else {
      ElMessage({type: 'error', message: '保存失败'})
      resolve(null);
    }
  });
};

const getUserTemplate = async (id: string) => {
  loadingPreview.value = true
  const data = await getResumeJsonById(id);
  if (data.code === 0) {
    HJNewJsonStore.value = JSON.parse(data.data.templateJson);
    HJNewJsonStore.value.props.title = HJNewJsonStore.value.config.title;
    resumeId.value = id
    loadingPreview.value = false;
  }
};
const getUserTemplateList = async () => {
  let params = {
    page: 1,
    limit: 100
  };
  loadingList.value = true
  const data = await getResumeList(params.page, params.limit);
  if (data.code === 0) {
    loadingList.value = false
    legoCreateList.value = data.data.list;
    legoCreateList.value.map((item: any) => {
      item.previewUrl = item.templateCover;
    });
  } else {
    ElMessage.error(data.message);
  }
};

const handleCommand = (command: number) => {
  selecting.value = command;
  if (selecting.value !== -1) {
    getUserTemplate(legoCreateList.value[selecting.value].id);
  }
}

const getResumeId = () => {
  if (selecting.value !== -1) {
    return legoCreateList.value[selecting.value].id;
  } else {
    return '';
  }
}

watch(
    () => selectedModuleId.value,
    (newVal) => {
      if (newVal) {
        selectedModule.value = useGetSelectedModule(newVal);
        dialogVisible.value = true
      }
    }
)

const saveResume = () => {
  saveDataToLocal();
  // 在这里添加保存简历的逻辑
  ElMessage.success('简历已保存');
};

const reAnalyse = () => {
  // 在这里添加重新分析简历的逻辑
  // ElMessage.success('简历已重新分析');
  router.push({
    name: 'analyse',
    params: {
      id : resumeId.value
    }
  });
};

const goBack = () => {
  showNavbar()
  router.go(-1);
};
</script>
<style>
.left-dialog {
  width: 50vw; /* 宽度为视口宽度的 60% */
  .el-dialog__header {
    padding: 20px 24px 16px;
    background: linear-gradient(135deg, #fdfcfb 0%, #f1e5dc 100%);
    border-bottom: 1px solid #f0f0f0;

    .el-dialog__title {
      font-size: 18px;
      font-weight: 600;
      color: #333;
    }
  }

  .el-dialog__body {
    max-height: 600px;
    overflow-y: auto;

    .empty-state {
      display: flex;
      align-items: center;
      justify-content: center;
      height: 100%;
      color: #999;
      font-size: 16px;
    }
  }

  .el-dialog__close {
    font-size: 18px;
    color: #666;

    &:hover {
      color: #333;
    }
  }
}
</style>
<style scoped>
.app-container {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  background-color: #f0f4ff;
  font-family: 'PingFang SC', 'Microsoft YaHei', sans-serif;
}

.header {
  padding: 5px;
  background-color: white;
  border-bottom: 1px solid #e0e0e0;
  display: flex;

}

.back-button {
  background: none;
  border: none;
  cursor: pointer;
  padding: 8px;
  color: #666;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  justify-content: center;
  min-width: 36px;
  height: 48px;
}

.back-button:hover {
  background-color: #f5f5f5;
  color: #333;
}

.title {
  width: 100%;
  padding: 5px 15px;
  font-size: 24px;
  font-weight: bolder;
  text-align: center; /* 文本居中 */
  display: block; /* 确保文本居中效果 */
}

.dropdown-row {
  width: 100%;
  padding-left: 3rem;
  padding-top: 1rem;
}

.el-dropdown-link {
  cursor: pointer;
  color: var(--el-color-primary);
  display: flex;
  align-items: center;
  font-size: 18px;
  font-weight: bold;
}

.main-content {
  display: flex;
  justify-content: center;
  flex: 1;
  padding: 10px;
  gap: 2.5rem;
}

.resume-section {
  flex: 3;
  max-width: 830px;
  overflow: hidden;
  margin-left: 1rem;
}

.resume-preview {
  flex: 1;
  height: 75vh;
  overflow-y: auto;
  border-radius: 20px;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}

.resume-container {
  margin: 0 auto;
  width: 820px;
  height: auto;
  overflow-y: auto
}

.empty-state {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 100%;
  padding: 2rem;
  text-align: center;
  background-color: #ffffff;
  border-radius: 20px;
}

.empty-icon {
  font-size: 64px;
  color: #c0c4cc;
  margin-bottom: 1.5rem;
}

.empty-title {
  font-size: 22px;
  color: #303133;
  margin-bottom: 1rem;
  font-weight: 500;
}

.empty-desc {
  font-size: 16px;
  color: #909399;
  max-width: 80%;
  line-height: 1.6;
  margin-bottom: 2rem;
}

.ai-chat-section {
  flex: 2;
  display: flex;
  flex-direction: column;
  height: 82vh;
  max-width: 45vw;
  margin-right: 2rem;
  background-color: #f8f8f5;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
  overflow: hidden;
}

.button-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
  gap: 40px;
}

.save-button {
  background-color: #4285f4;
  color: white;
  border: none;
  padding: 10px 40px;
  border-radius: 4px;
  font-size: 16px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.save-button:hover {
  background-color: #3367d6;
}

.reanalyse-button {
  background-color: #2EC4B6;
  color: white;
  border: none;
  padding: 10px 40px;
  border-radius: 4px;
  font-size: 16px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.reanalyse-button:hover {
  background-color: #5EEAD4;
}

/* 响应式设计 */
@media (max-width: 1024px) {
  .main-content {
    flex-direction: column;
  }

  .resume-section, .ai-chat-section {
    width: 100%;
  }
}
</style>